import http from '@/trnall/request/index'
// import share from '@/trnall/share';

const state = {
	shop: {}, // 商城信息
	orderVerifyNum: uni.getStorageSync("order_verify_num") || 0,
	goodsFeedback: [{
		index: 0,
		text: '无需反馈',
		min: 5, //最少返现的金额
	}, {
		index: 1,
		text: '优质反馈',
		min: 10,
	}, {
		index: 2,
		text: '优质反馈(需含图文)',
		min: 10
	}],
	shopCategory: uni.getStorageSync("shop_category") || [],
	/* wechat: {}, // 微信配置
	share: {}, // 分享配置
	payment: {}, // 支付配置
	addons: [], // 插件配置
	chat: uni.getStorageSync("chat") || {}, // 客服配置
	store: {}, // 商城信息
	tabbarData: [], //自定义底部导航数据
	recharge: uni.getStorageSync("recharge") || {}, //充值配置

	homeTemplate: [], // 首页模板数据
	userTemplate: [], // 个人中心模板数据
	floatData: {}, // 悬浮按钮数据
	popupData: {}, // 弹窗数据
	hasTemplate: true, //是否有模板数据
	shareInfo: {}, // 默认分享数据
	locationAddressData: {} */
}
const getters = {
	orderVerifyNum: state => state.orderVerifyNum,
	goodsFeedback: state => state.goodsFeedback,
	shopCategory: state => state.shopCategory,
	/* initShop: state => state.shop,
	initStore: state => state.store,
	initShare: state => state.share,
	initPayment: state => state.payment,
	initAddons: state => state.addons,
	initChat: state => state.chat,
	initWechat: state => state.wechat,
	initRecharge: state => state.recharge,

	hasTemplate: state => state.hasTemplate,
	homeTemplate: state => state.homeTemplate,
	locationAddressData: state => state.locationAddressData,
	userTemplate: state => state.userTemplate,
	floatData: state => state.floatData,
	popupData: state => state.popupData,
	tabbarData: state => state.tabbarData,

	shareInfo: state => state.shareInfo */
}


const actions = {
	// 初始化数据
	async appInit({
		commit,
		dispatch
	}, options) {
		// const result = await http('common.init');

		// if (result.code === 1) {
		// 	commit('CONFIG', result.data);
		// 	if (!options?.query?.token) {
		// 		dispatch('autoLogin');
		// 	}
		// 	return result.data;
		// }
		console.log('appInit')
		dispatch('autoLogin');
		return false;
	},
	async getOrderVerifyNum({
		commit,
		dispatch
	}, options) {
		console.log('getOrderVerifyNum')
		let selectedShopId = uni.getStorageSync('selectedShopId');
		http('order.orderVerifyNum', {
				shop_id: selectedShopId
			}).then(res => {
				console.log('getOrderVerifyNum', res)
				if (res.code === 1) {
					commit('orderVerifyNum', res.data)
				} else {
					commit('orderVerifyNum', 0)
				}
			})
			.catch(err => {
				commit('orderVerifyNum', 0)
			})
	},
	async getShopCategory({
		commit,
		dispatch
	}, options) {
		console.log('getShopCategory')
		http('user.shopCategory', {}).then(res => {
				console.log('getShopCategory', res)
				if (res.code === 1) {
					commit('shopCategory', res.data)
				} else {
					commit('shopCategory', [])
				}
			})
			.catch(err => {
				commit('shopCategory', [])
			})
	},
	async goAdmin({
		commit,
		dispatch
	}, id = 0) {
		let $vx = this;
		let that = this._vm;
		// if (id > 0) {
		commit('selectId', id);
		commit('currentShopIndex', 0)
		that.$util.loading('进入中');
		setTimeout(() => {
			uni.hideLoading();
			that.$util.jump('/pages/index/index', 'reLaunch');
		}, 1000)
		/* } else {
			commit('selectId', id);
		} */
	}
	/* 
		// 获取模板数据
		async getTemplate({
			commit
		}, options) {
			console.log('执行shopro.getTemplate', options)
			uni.showLoading({
				title: '加载中',
				mask: true,
			})
			let meLocation = uni.getStorageSync('longitudeAndLatitude');
			let lat = 33.46723; //腾讯：33.44241   高德：33.441964
			let lng = 114.87562; //腾讯：114.871234 高德：114.871218
			if (options?.query?.location) {
				lat = options?.query?.location.latitude;
				lng = options?.query?.location.longitude;
			} else if (meLocation && meLocation.latitude && meLocation.longitude) {
				lat = meLocation.latitude;
				lng = meLocation.longitude;
			}
			let shop_id = 0;
			// #ifdef H5
			if (options?.query.shop_id) {
				shop_id = options.query.shop_id;
			}
			// #endif

			// #ifdef MP
			if (options?.query.scene) {
				let scene = decodeURIComponent(options?.query.scene);
				let sceneObj = scene.split('=');
				if (sceneObj[0] === 'shop_id') {
					shop_id = sceneObj[1]
				}
			}
			// #endif
			let requestData = {
				lat,
				lng
			};
			const result = await http('common.template', requestData);
			if (result.code === 1) {
				commit("hasTemplate", true);
				commit('TEMPLATE', result.data);
				return result.data;
			} else {
				commit("hasTemplate", false);
				return false;
			}
		},

		// 同步路由到后端
		syncPages({
			commit
		}) {
			http('common.syncPages', {
				data: ROUTES,
			})
		},
		async getLocation({
			commit
		}, params) {
			let that = this;
			// uni.showLoading({
			// 	title: '定位中',
			// 	mask: true,
			// })
			if (params == undefined || JSON.stringify(params) == "{}" || !params.hasOwnProperty('num')) {
				params = {
					num: 0
				};
			}
			params.num = params.num + 1;
			uni.showToast({
				title: params.num
			})
			console.log('that', params, that)
			return new Promise((resolve, reject) => {
				console.log(params)
				if (params.num > 2) {
					//定位三次还未定位成功，设置默认位置为天安门
					let defaultLocation = {
						latitude: 39.908821,
						longitude: 116.397469
					};
					uni.setStorageSync('longitudeAndLatitude', defaultLocation);
					resolve(defaultLocation);
					return;
				}
				uni.getLocation({
					type: 'wgs84', //默认为 wgs84 返回 gps 坐标，gcj02 返回国测局坐标，可用于 uni.openLocation 和 map 组件坐标，App 和 H5 需配置定位 SDK 信息才可支持 gcj02。
					isHighAccuracy: true,
					success: res => {
						uni.setStorageSync('longitudeAndLatitude', res);
						console.log('getLocation定位成功,返回GPS' + (new Date().getTime()), params,
							res)
						resolve(res)
					},
					fail: function(err) {
						console.log('定位授权失败', err);
						uni.authorize({
							scope: 'scope.userLocation',
							complete(res) {
								console.log('authorize-com', res);
								if (res.errMsg == 'authorize:ok') {
									//手机定位没有开启
									uni.showModal({
										title: '提示',
										content: '您没有打开定位服务功能，请确认您已打开定位服务功能' +
											params.num,
										showCancel: false, // 不显示取消按钮
										success: async res => {
											if (res.confirm) {
												console.log('用户点击确定,指定定位',
													params, that);
												return resolve(await that
													.dispatch(
														"getLocation",
														params
													));
											}
										}
									});
								} else {
									uni.showModal({
										title: '提示',
										content: '请授权定位服务',
										showCancel: false, // 不显示取消按钮
										success() {
											console.log('进入授权定位服务开启功能')
											uni.openSetting({
												success: async res => {
													return resolve(
														await that
														.dispatch(
															"getLocation",
															params
														));
												},
												fail: async err => {

												}
											});
										}
									});
								}
							}
						})
					}
				});
			}).then(res => {
				console.log('ther', res)
				return res
			}).catch();
		},

		//QQ逆地址解析
		async QqRegeo({
			commit
		}, options) {
			console.log('执行QqRegeo开始，参数', options)
			let meLocation = uni.getStorageSync('longitudeAndLatitude');
			let lat = 33.46723; //腾讯：33.44241   高德：33.441964
			let lng = 114.87562; //腾讯：114.871234 高德：114.871218
			if (options?.query?.location) {
				console.log('用参数经纬度')
				lat = options?.query?.location.latitude;
				lng = options?.query?.location.longitude;
			} else if (meLocation && meLocation.latitude && meLocation.longitude) {
				console.log('用缓存经纬度')
				lat = meLocation.latitude;
				lng = meLocation.longitude;
			}
			console.log('执行QqRegeo地址解析，参数', {
				lat: lat,
				lng: lng
			})
			let url =
				`https://apis.map.qq.com/ws/geocoder/v1/?location=${lat},${lng}&key=IRQBZ-ETXK6-SSHSO-EMXN2-7PVQ7-Q2FR6&get_poi=0`;
			const [error, ret] = await uni.request({
				url: url
			});
			console.log('QQ逆坐标解析', ret)
			if (ret.statusCode == 200 && ret.data.status === 0) {
				let locationAddressData = {
					address_component: ret.data.result.address_component,
					formatted_addresses: ret.data.result.formatted_addresses
				};
				state.locationAddressData = locationAddressData
				uni.setStorageSync('regeo', locationAddressData)
			} else {
				console.log('%c2逆地址解析失败，请检查是否在env中配置地图key', 'color:green;background:yellow');
			}
		},
		//gps转腾讯坐标
		async GPS2QQ({
			commit
		}, options) {
			console.log('执行GPS2QQ开始，参数', options)
			if (options?.query?.location) {
				let lat = options?.query?.location.latitude;
				let lng = options?.query?.location.longitude;
				let url =
					`https://apis.map.qq.com/ws/coord/v1/translate?locations=${lat},${lng}&type=1&key=IRQBZ-ETXK6-SSHSO-EMXN2-7PVQ7-Q2FR6`;
				const [error, res] = await uni.request({
					url: url
				})
				if (res.statusCode == 200 && res.data.status === 0) {
					console.log('坐标转换', res)
					uni.setStorageSync('longitudeAndLatitude', {
						latitude: res.data.locations[0].lat,
						longitude: res.data.locations[0].lng
					});
				} else {
					console.log('坐标转换失败')
				}
			}
		}, */
}


const mutations = {
	orderVerifyNum(state, data) {
		console.log('mutations', data)
		state.orderVerifyNum = data;
		uni.setStorageSync('order_verify_num', data);
		if (data > 0) {
			uni.setTabBarBadge({
				index: 2,
				text: data + ''
			})
		} else {
			uni.removeTabBarBadge({
				index: 2,
			})
		}
	},
	shopCategory(state, data) {
		console.log('shopCategory', data)
		state.shopCategory = data;
		uni.setStorageSync('shop_category', data);
	}
	/* CONFIG(state, payload) {
		Object.keys(payload).forEach(k => {
			state[k] = payload[k];
			if (k === 'chat') {
				uni.setStorageSync("chat", payload[k]);
			}
			if (k === 'recharge') {
				uni.setStorageSync("recharge", payload[k])
			}
		})
	},

	TEMPLATE(state, data) {
		console.log('store.TEMPLATE.data', data)
		console.log('store.TEMPLATE.state', state)
		state.template = data;
		state.homeTemplate = data.home
		state.userTemplate = data.user
		state.floatData = data['float-button']?. [0]?.content
		state.popupData = data?.popup?. [0]?.content
		state.tabbarData = data?.tabbar?. [0]?.content
	},

	hasTemplate(state, data) {
		state.hasTemplate = data
	},
	// 弹窗一次的话，关闭的时候删除数据。
	delPopup(state, index) {
		let popupData = state.popupData;
		popupData.list.splice(index, 1)
		state.template = popupData;
	},
	shareInfo(state, shareInfo) {
		state.shareInfo = shareInfo;
	} */
}


export default {
	state,
	mutations,
	actions,
	getters
}
